package com.zhenyi.core;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.cenjiawen.common.IndexController;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import cn.hutool.core.util.PageUtil;

public class ZIndexController extends IndexController {

	protected Cache cache = Redis.use();

	protected String renderSuccess(String key, Object object) {
		final int expireSeconds = 7200;
		String json = cache.get(key);
		if (StrKit.notBlank(json)) {
			cache.expire(key, expireSeconds);
			renderJson(json);
			return json;
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("status", 200);
		map.put("info", object);
		setAttr("status", 200);
		setAttr("info", object);

		json = JsonKit.toJson(object);
		cache.setex(key, expireSeconds, json);
		renderJson(json);
		return json;
	}

	protected Kv getSimpleKv(String... names) {
		Kv kv = Kv.create();
		for (String name : names) {
			String value = getPara(name);
			if (StrKit.isBlank(value)) {
				continue;
			}
			setAttr(name, value);
			kv.set(name, value);
		}
		return kv;
	}

	protected void setData(String name, Object info) {
		if (info == null) {
			return;
		}
		String json = VueUtils.getVueData(info);
		setAttr(name, json);
	}

	protected void setRainbow(Page<?> pages) {
		Integer requestPage = getParaToInt("page");

		HttpServletRequest request = getRequest();
		String url = request.getRequestURL().toString();
		String queryurl = request.getQueryString();
		if (StrKit.notBlank(queryurl)) {
			if (requestPage != null) {
				queryurl = queryurl.replace("&page=" + requestPage, "");
				queryurl = queryurl.replace("page=" + requestPage, "");
				if (StrKit.notBlank(queryurl)) {
					url = url + "?" + queryurl + "&page=";
				} else {
					url = url + "?page=";
				}
			} else {
				url = url + "?" + queryurl + "&page=";
			}
		} else {
			url = url + "?page=";
		}
		int pageTotal = pages.getTotalPage();
		int pageTotalRow = pages.getTotalRow();
		int page = pages.getPageNumber();
		int[] rainbow = PageUtil.rainbow(pages.getPageNumber(), pageTotal);
		setAttr("rainbow", rainbow);
		setAttr("pageUrl", url);
		setAttr("pageTotalRow", pageTotalRow);
		setAttr("pageSize", pages.getPageSize());
		setAttr("pageCurrent", page);
	}
}
